package com.xingfly.service;

import com.xingfly.security.jwt.util.JwtConstants;
import com.xingfly.security.jwt.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by SuperS on 2016/12/22.
 */
@Service
public class JwtService {
    private static final String KEY_NAME = "token:";
    private static final String BLACK_LIST = "black:list:";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 存储id和token到redis
     *
     * @param token  令牌
     * @param userId 用户ID
     */
    public void save(Long userId, String token) {
        redisTemplate.opsForValue().set(KEY_NAME + userId, token);
        //过期时间7天
        redisTemplate.expire(KEY_NAME + userId, JwtConstants.TOKEN_EXPIRATION_TIME, TimeUnit.SECONDS);
    }

    /**
     * 删除token
     * @param userId 用户ID
     */
    public void delete(Long userId) {
        //直接设置过期时间为0秒
        redisTemplate.expire(KEY_NAME + userId, 0, TimeUnit.SECONDS);
    }

    /**
     * 获取Token
     *
     * @param userId 用户ID
     */
    public String getToken(Long userId) {
        return redisTemplate.opsForValue().get(KEY_NAME + userId);
    }


    /**
     * 添加到黑名单中
     *
     * @param token 令牌
     */
    public void addToBlackList(String token) {
        Date expiration = jwtTokenUtil.getExpirationDateFromToken(token);
        Date now = new Date();
        redisTemplate.opsForValue().set(token, token);
        redisTemplate.expire(token, expiration.getTime() - now.getTime(), TimeUnit.MILLISECONDS);
    }

    /**
     * 在黑名单中 就返回 真
     *
     * @param token 令牌
     */
    public boolean isInBlackList(String token) {
        return redisTemplate.opsForValue().get(token) != null;
    }


}
